//
//  AreaController.swift
//  weather
//
//  Created by smile on 2020/10/23.
//

import UIKit

//导入响应式编程框架
import RxSwift

//导入发布订阅框架
import SwiftEventBus


class AreaController: UIViewController {
    
    @IBOutlet weak var editItem: UIBarButtonItem!
    
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    var isShowSearch = false
    
    var currentIndex = -1
    
    var topTitle = ""
    
    
    //负责对象销毁
    //这个功能类似NotificationCenter的removeObserver
    let disposeBag=DisposeBag()
    
    /// 区域列表数据源
    var dataArray:[Area] = []
    
    /// 搜索的区域列表数据源
    var searchDataArray:[Area] = []

    override func viewDidLoad() {
        super.viewDidLoad()
//        topTitle=navigationController?.navigationBar.topItem?.title ?? ""
//        navigationController?.navigationBar.topItem?.title=""
//        navigationController?.navigationBar.tintColor = .black
        
        textField.delegate=self
        
        //监听编辑后文本变化
        textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

        fetchData()
    }
    
    @objc func textFieldDidChange() {
//        print("textFieldDidChange:\(textField.text?.count)")
        
        searchArea()
    }
    
    func fetchData() {
//        let area=Area()
//        area.name = "小店区"
//        area.formatted_address = "山西太原"
//
//        area.location = Location()
//        area.location.lat = 37.785834
//        area.location.lng = 122.406417
//
//        let area1 = Area()
//        area1.name = "北京"
//        area1.formatted_address = "中国"
//        area1.location = Location()
//        area1.location.lat = 40.22077
//        area1.location.lng = 116.23128
//
//        dataArray.append(area1)
//
//        let area2 = Area()
//        area2.name = "成都"
//        area2.formatted_address = "中国"
//        area2.location = Location()
//        area2.location.lat = 30.65984
//        area2.location.lng = 104.10194
//
//        dataArray.append(area2)
        
        //加载用户选择的城市
        if let d=PreferenceUtil.getAreas() {
            dataArray = dataArray + d
        }
        
        tableView.reloadData()
        
        refrshEditTitle()
    }
    
    func refrshEditTitle() {
        if isShowSearch || dataArray.count == 0 {
            editItem.image = nil
        }else{
            editItem.image = UIImage(named: "Edit")
        }
        
    }
    

    func searchArea() {
        //清空数据
        searchDataArray.removeAll()
        
        let data = textField.text!.trim()!
        
        if data.isEmpty {
            //显示原来区域
            isShowSearch=false
            
            tableView.reloadData()
            
            refrshEditTitle()
        }else{
            isShowSearch=true
            
            refrshEditTitle()
            tableView.isEditing=false
            
            //搜索区域
            WeatherApi.shared.place(data: data).subscribe(onNext: { response in
                print("searchArea success:\(response)")
                
                if "ok" != response.status {
                    self.showErrorAlert()
                    return
                }
                
                self.showData(response.places)
                
            }, onError: { data in
            self.showErrorAlert()
        }, onCompleted: nil, onDisposed: nil).addDisposableTo(disposeBag)
        }
    }
    
    func showErrorAlert() {
        let alertController=UIAlertController(title: "错误提示", message: "网络请求失败，请检查网络，并稍后再试，如果还有问题请在设置联系我们反馈.", preferredStyle: .alert)
        
        let confirmAction=UIAlertAction(title: "确定", style: .default, handler: nil)

            //将动作添加到控制器
            alertController.addAction(confirmAction)

            //显示
            present(alertController, animated: true, completion: nil)
    }
    
    func showData(_ data:[Area]?) {
        if let data = data{
            //有数据
            
            searchDataArray = data
            isShowSearch=true
        }else{
            //没有数据
            isShowSearch=false
        }
        
        tableView.reloadData()
        
        refrshEditTitle()
    }

    @IBAction func onEditClick(_ sender: UIBarButtonItem) {
        if editItem.title != "" {
            tableView.isEditing = !tableView.isEditing
        }
        
//        textField.isHidden = tableView.isEditing
    }
    
}


extension AreaController:UITableViewDataSource,UITableViewDelegate{
    
    
    /// 返回当前位置Cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取Cell
        let cell = tableView.dequeueReusableCell(withIdentifier: CELL, for: indexPath) as! UITableViewCell
        
        let data:Area!
        if isShowSearch {
            data = searchDataArray[indexPath.row]
        }else{
            data = dataArray[indexPath.row]
        }
        
        //绑定数据
        cell.textLabel?.text=data.name
        cell.detailTextLabel?.text=data.formatted_address
        
        //返回cell
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return isShowSearch ? searchDataArray.count : dataArray.count
    }
    
    /// 点击Cell回调
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if isShowSearch {
            //取出数据源
            let data = searchDataArray[indexPath.row]
            
            //保存当前点击的城市
            dataArray.append(data)
            
            currentIndex=dataArray.count-1
        }else{
            currentIndex=indexPath.row
        }
        
        //关闭当前界面
        navigationController!.popViewController(animated: true)

    }
    
    override func viewWillDisappear(_ animated: Bool) {
//        navigationController?.navigationBar.topItem?.title=topTitle
        
        super.viewWillDisappear(animated)
        
        if currentIndex != -1 {
            //保存数据
            PreferenceUtil.setAreas(dataArray)
            
            //把选择索引分发出去
            SwiftEventBus.post(ON_SELECT_AREA, sender: currentIndex)
        }
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    
    // MARK: - 列表编辑相关
        
    /// 当前Index对应的Cell是否可以编辑
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return !isShowSearch
    }
    
    /// 编辑样式
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    /// 编辑按钮的标题
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    /// 点击编辑按钮后的动作
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - editingStyle: <#editingStyle description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        //从数据源中移除
        dataArray.remove(at: indexPath.row)
        
        //删除cell
        tableView.deleteRows(at: [indexPath], with: .automatic)
        
        currentIndex=0
        
        refrshEditTitle()
    }
    
    
    /// 是否能移动
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#description#>
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    
    /// 移动cell是回调
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - sourceIndexPath: <#sourceIndexPath description#>
    ///   - destinationIndexPath: <#destinationIndexPath description#>
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
        let source = dataArray[sourceIndexPath.row]
        
        dataArray.remove(at: sourceIndexPath.row)
        
        dataArray.insert(source, at: destinationIndexPath.row)
        
        currentIndex = 0
    }
}

// MARK: - TextView代理
extension AreaController: UITextFieldDelegate{
    
    
    /// 开始
    /// - Parameter textField: <#textField description#>
    func textFieldDidBeginEditing(_ textField: UITextField) {
        tableView.isEditing = false
    }
    
    
    /// 编辑中
    /// - Parameters:
    ///   - textField: <#textField description#>
    ///   - range: <#range description#>
    ///   - string: <#string description#>
    /// - Returns: <#description#>
//    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//
//
//
//        return true
//    }
    
    
    
    
    /// 结束编辑
    /// - Parameter textField: <#textField description#>
//    func textFieldDidEndEditing(_ textField: UITextField) {
//        editItem.title = "编辑"
//    }
    
}
